package com.eloo.otsclient.core;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import javax.imageio.ImageReader;
import javax.swing.ImageIcon;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eloo.otsclient.ui.OTSClientUI;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.FrameWindow;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlHiddenInput;
import com.gargoylesoftware.htmlunit.html.HtmlImage;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;

public class OTSLogin extends OTSBasicPage{


	private   HtmlPage loginSuccessPage=null;

	private HtmlTextInput qrCode;
	private HtmlPage initLoginPage;
	private String loginName;
	private String passWord;
	//private OTSQueryTicket otsquery;
	private HtmlPage enterURL = null; 
	private HtmlTextInput username;
	private HtmlPasswordInput password ;
	/**
	 * Starting Login
	 * @param name
	 * @param pw
	 * @param webClient
	 * @throws IOException 
	 * @throws MalformedURLException 
	 * @throws FailingHttpStatusCodeException 
	 */
	
	
	
	public OTSLogin() {    
		this.webClient = OTSWebClient.getRootWebClient();   
		OTSClientUI.getJbuttonLogin().addActionListener(loginListerner);    
		try {
			enterURL = webClient.getPage(OTSConstants.ENTER_URL); 
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println(e1.getMessage());
		}
	}
  
 
	public void initLoginPage(){ 
		try {
		enterURL = webClient.getPage(OTSConstants.ENTER_URL);
		final List<FrameWindow> window = enterURL.getFrames();
		initLoginPage = (HtmlPage) window.get(0).getEnclosedPage();
		logger.info(initLoginPage.asText()); 
		final HtmlForm form = initLoginPage.getFormByName("loginForm");
		form.setAttribute("target", "_new"); 
		qrCode = form.getInputByName("randCode");
		// final HtmlHiddenInput loginRand =  form.getInputByName("loginRand");  
		final HtmlHiddenInput refundFlag = form.getInputByName("refundFlag");
		refundFlag.setValueAttribute("Y");
		final HtmlHiddenInput refundLogin = form.getInputByName("refundLogin");
		refundLogin.setValueAttribute("N");
		username = form.getInputByName("loginUser.user_name");
		password = form.getInputByName("user.password");
		final HtmlImage him = (HtmlImage) form.getElementsByTagName("img").get(0); 
		ImageReader imr = him.getImageReader(); 
		BufferedImage myPicture = imr.read(0);
		OTSClientUI.getJlabelViewQR().setIcon(new ImageIcon(myPicture));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void invokeLoginData(String name ,String pw){  
		username.setValueAttribute(loginName); 
		password.setValueAttribute(passWord);  
	}

	private HtmlPage newLoginPage() {
		System.out.println(OTSClientUI.getJtextQRcode().getText().trim());
		HtmlPage newEnterURL = null;
		try { 
			newEnterURL = this.webClient.getPage(OTSConstants.ENTER_URL);
		} catch (Exception e) {
			 
			e.printStackTrace();
		}
		logger.info(enterURL.asText()); 
		return newEnterURL;

	}

 

	ActionListener  loginListerner=new ActionListener() { 
		public void actionPerformed(ActionEvent e) { 
			loginName = OTSClientUI.getJtextLogin().getText().trim();
			passWord = OTSClientUI.getJtextPassword().getText().trim();   
			System.out.println(e.getActionCommand()+e.getSource());  
			invokeLoginData(loginName,passWord);  
			qrCode.setValueAttribute(OTSClientUI.getJtextQRcode().getText().trim()); 
			logger.info("loginSuccessPage is loading..");
			ScriptResult sr = initLoginPage.executeJavaScript("checkAysnSuggest();"); 
			webClient.waitForBackgroundJavaScriptStartingBefore(30000);
			webClient.waitForBackgroundJavaScript(30000);
			loginSuccessPage = (HtmlPage) sr.getNewPage();
			logger.info("loginSuccessPage " + loginSuccessPage.asXml()); 
			if (loginSuccessPage != null && !loginSuccessPage.getUrl().toString().contains(OTSConstants.LOGIN_URL)) {
				logger.info("loginSuccessPage " + loginSuccessPage.asXml()); 
				OTSClientUI.getJbuttonLogin().setText(OTSConstants.LOGIN_SUC);
				logger.info("loginSuccessPage " + loginSuccessPage.asXml());   
		 
				OTSClientUI.updateQueryUI();
			} else {   
				enterURL=newLoginPage();
				initLoginPage();
				//invokeLoginData(loginName,passWord); 
				OTSClientUI.getJbuttonLogin().setText(OTSConstants.RE_LOGIN);
				OTSClientUI.getJbuttonLogin().grabFocus();
				return;
			}
		}
	};

}
